<template>
  <div>
    <t-loading :loading="loading" :text="loadingText" fullscreen />
    <div :header="isAdd ? '添加物料' : '编辑物料'" width="70%">
      <t-collapse :default-value="[0, 1, 2]">
        <t-collapse-panel header="基础信息">
          <div>
            <t-form :data="formData" :colon="true" label-width="120px" label-align="right">
              <t-row :gutter="15">
                <t-col :span="3" class="form_col">
                  <t-form-item label="BOM版本" name="FNumber">
                    <t-input
                      v-if="isShowSpan(false)"
                      v-model="formData.FNumber"
                      placeholder="保存时自动生成"
                      readonly
                    />
                    <span v-else class="info_span">{{ formData.FNumber }}</span>
                  </t-form-item>
                </t-col>

                <t-col :span="3" class="form_col">
                  <t-form-item label="BOM简称" name="FName">
                    <t-input v-if="isShowSpan(false)" v-model="formData.FName" placeholder="请输入内容" />
                    <span v-else class="info_span">{{ formData.FName }}</span>
                  </t-form-item>
                </t-col>
              </t-row>
            </t-form>
          </div>
        </t-collapse-panel>

        <t-collapse-panel header="主产品">
          <div>
            <t-form :data="formData" :colon="true" label-width="120px" label-align="right">
              <t-row :gutter="15">
                <t-col :span="3" class="form_col">
                  <t-form-item label="单据类型" name="FBILLTYPE">
                    <t-select
                      v-if="isShowSpan(false)"
                      v-model="formData.FBILLTYPE"
                      placeholder="请选择类型"
                      class="demo-select-base"
                    >
                      <t-option value="WLQD01_SYS" label="物料清单"> 物料清单 </t-option>
                      <!-- <t-option
                        v-for="(item, index) in metaData.FBILLTYPE"
                        :key="index"
                        :value="item.Value"
                        :label="item.Caption"
                      >
                        {{ item.Caption }}
                      </t-option> -->
                    </t-select>
                    <span v-else class="info_span">{{ formData.FBILLTYPEName }}</span>
                  </t-form-item>

                  <t-form-item label="BOM分类" name="FBOMCATEGORY">
                    <t-select
                      v-if="isShowSpan(false)"
                      v-model="formData.FBOMCATEGORY"
                      placeholder="请选择类型"
                      class="demo-select-base"
                      clearable
                    >
                      <t-option
                        v-for="(item, index) in metaData.FBOMCATEGORY"
                        :key="index"
                        :value="item.Value"
                        :label="item.Caption"
                      >
                        {{ item.Caption }}
                      </t-option>
                    </t-select>
                    <span v-else class="info_span">{{ formData.FBOMCATEGORYName }}</span>
                  </t-form-item>

                  <t-form-item label="BOM用途" name="FBOMUSE">
                    <t-select
                      v-if="isShowSpan(false)"
                      v-model="formData.FBOMUSE"
                      placeholder="请选择类型"
                      class="demo-select-base"
                      clearable
                    >
                      <t-option
                        v-for="(item, index) in metaData.FBOMUSE"
                        :key="index"
                        :value="item.Value"
                        :label="item.Caption"
                      >
                        {{ item.Caption }}
                      </t-option>
                    </t-select>
                    <span v-else class="info_span">{{ formData.FBOMUSEName }}</span>
                  </t-form-item>

                  <t-form-item label="BOM分组" name="FGroup">
                    <t-select
                      v-if="isShowSpan(false)"
                      v-model="formData.FGroup"
                      placeholder="请选择"
                      class="demo-select-base"
                      clearable
                    >
                      <t-option
                        v-for="(item, index) in metaData.FGroup"
                        :key="index"
                        :value="item.value"
                        :label="item.label"
                      >
                        {{ item.label }}
                      </t-option>
                    </t-select>
                    <span v-else class="info_span">{{ formData.FGroupName }}</span>
                  </t-form-item>
                </t-col>

                <t-col :span="3" class="form_col">
                  <t-form-item label="父项物料编码" name="FMaterialNumber">
                    <t-input v-if="isShowSpan(false)" v-model="formData.FMaterialNumber" placeholder="">
                      <template #suffixIcon>
                        <t-icon name="search" :style="{ cursor: 'pointer' }" @click="clickShowMaterSelect" />
                        <!-- <search-icon  /> -->
                      </template>
                    </t-input>
                    <span v-else class="info_span">{{ formData.FMATERIALIDName }}</span>
                  </t-form-item>

                  <t-form-item label="物料名称" name="FITEMNAME">
                    <t-input v-if="isShowSpan(false)" v-model="formData.FITEMNAME" placeholder="请输入内容" />
                    <span v-else class="info_span">{{ formData.FITEMNAME }}</span>
                  </t-form-item>
                  <t-form-item label="规格型号" name="FITEMMODEL">
                    <t-input v-if="isShowSpan(false)" v-model="formData.FITEMMODEL" placeholder="请输入内容" />
                    <span v-else class="info_span">{{ formData.FITEMMODEL }}</span>
                  </t-form-item>
                  <t-form-item label="物料属性" name="FITEMPPROPERTY_NAME">
                    <t-input v-if="isShowSpan(false)" v-model="formData.FITEMPPROPERTY_NAME" placeholder="请输入内容" />
                    <span v-else class="info_span">{{ formData.FITEMPPROPERTY_NAME }}</span>
                  </t-form-item>
                </t-col>

                <!-- <t-col :span="3" class="form_col">
                  <t-form-item label="单据类型" name="FBILLTYPE">
                    <span v-else class="info_span">{{ formData.FBILLTYPEName }}</span>
                  </t-form-item>

                  <t-form-item label="BOM分类" name="FBOMCATEGORY">
                    <t-select v-if="isShowSpan(false)" v-model="formData.FBOMCATEGORY" placeholder="请选择类型"
                      class="demo-select-base" clearable>
                      <t-option v-for="(item, index) in metaData.FBOMCATEGORY" :key="index" :value="item.Value"
                        :label="item.Caption">
                        {{ item.Caption }}
                      </t-option>
                    </t-select>
                    <span v-else class="info_span">{{ formData.FBOMCATEGORYName }}</span>
                  </t-form-item>

                  <t-form-item label="BOM用途" name="FBOMUSE">
                    <t-select v-if="isShowSpan(false)" v-model="formData.FBOMUSE" placeholder="请选择类型"
                      class="demo-select-base" clearable>
                      <t-option v-for="(item, index) in metaData.FBOMUSE" :key="index" :value="item.Value"
                        :label="item.Caption">
                        {{ item.Caption }}
                      </t-option>
                    </t-select>
                    <span v-else class="info_span">{{ formData.FBOMUSEName }}</span>
                  </t-form-item>

                  <t-form-item label="BOM分组" name="FGroup">
                    <t-select v-if="isShowSpan(false)" v-model="formData.FGroup" placeholder="请选择"
                      class="demo-select-base" clearable>
                      <t-option v-for="(item, index) in metaData.FGroup" :key="index" :value="item.value"
                        :label="item.label">
                        {{ item.label }}
                      </t-option>
                    </t-select>
                    <span v-else class="info_span">{{ formData.FGroupName }}</span>
                  </t-form-item>
                </t-col> -->
              </t-row>
            </t-form>
          </div>
        </t-collapse-panel>

        <t-collapse-panel header="子项明细">
          <div>
            <t-space style="display: flex; background-color: white; padding: 10px 10px">
              <t-link theme="primary" @click="clickUpload">上传模板</t-link>
              <t-link theme="primary" @click="addRow">新增行</t-link>
              <t-link theme="primary" @click="deleteRow">删除行</t-link>
              <!-- <t-link theme="primary" @click="insertRow">插入行</t-link> -->
              <t-link theme="primary" @click="copyRow">复制行</t-link>
              <!-- <t-link theme="primary" @click="upRow">上移</t-link> -->
              <!-- <t-link theme="primary" @click="downRow">下移</t-link> -->
              <t-link theme="primary" @click="clickCancel">返回</t-link>
              <!-- <t-link theme="primary" @click="clickSave(true)">暂存</t-link> -->
              <t-link theme="primary" @click="clickSave(false)">保存</t-link>
            </t-space>
            <t-table
              row-key="index"
              :data="subDataList"
              :columns="columns"
              :resizable="true"
              :loading="tableLoading"
              :stripe="stripe"
              bordered
              :selected-row-keys="selectedRowKeys"
              active-row-type="single"
              table-layout="auto"
              size="small"
              :pagination="pagination"
              cell-empty-content="-"
              lazy-load
              :select-on-row-click="true"
              @select-change="rehandleSelectChange"
              @row-click="handleRowClick"
              @cell-click="cellClick"
            >
              <!-- <template #FReplaceGroup="{ rowIndex, row }">
                <span>{{row.FReplaceGroup}}</span>
              </template> -->

              <template #FMATERIALIDCHILDNumber="{ rowIndex, row }">
                <t-input v-if="!row.FENTRYID" v-model="row.FMATERIALIDCHILDNumber" placeholder="">
                  <template #suffixIcon>
                    <t-icon
                      name="search"
                      :style="{ cursor: 'pointer' }"
                      @click="clickShowSubMaterSelect(rowIndex, row)"
                    />
                    <!-- <search-icon  /> -->
                  </template>
                </t-input>
                <span v-else>{{ row.FMATERIALIDCHILDNumber }}</span>
              </template>
              <template #FNUMERATOR="{ rowIndex, row, col }">
                <t-input
                  v-if="row[col.colKey + 'Show']"
                  id="input1"
                  v-model="row.FNUMERATOR"
                  placeholder=""
                  @blur="onBlur({ rowIndex, row, col })"
                >
                </t-input>
                <span v-else>{{ row.FNUMERATOR }}</span>
              </template>

              <template #FDENOMINATOR="{ rowIndex, row, col }">
                <t-input
                  v-if="row[col.colKey + 'Show']"
                  id="input1"
                  v-model="row.FDENOMINATOR"
                  placeholder=""
                  @blur="onBlur({ rowIndex, row, col })"
                >
                </t-input>
                <span v-else>{{ row.FDENOMINATOR }}</span>
              </template>
              <template #FPOSITIONNO="{ rowIndex, row, col }">
                <t-input
                  v-if="row[col.colKey + 'Show']"
                  id="input1"
                  v-model="row.FPOSITIONNO"
                  placeholder=""
                  @blur="onBlur({ rowIndex, row, col })"
                >
                </t-input>
                <span v-else>{{ row.FPOSITIONNO }}</span>
              </template>

              <template #F_ora_Base_Name="{ rowIndex, row }">
                <t-input v-model="row.F_ora_Base_Name" placeholder="">
                  <template #suffixIcon>
                    <t-icon
                      name="search"
                      :style="{ cursor: 'pointer' }"
                      @click="clickShowProjectSelect(rowIndex, row)"
                    />
                    <!-- <search-icon  /> -->
                  </template>
                </t-input>
              </template>

              <template #F_ora_Remark="{ rowIndex, row, col }">
                <t-input
                  v-if="row[col.colKey + 'Show']"
                  id="input1"
                  v-model="row.F_ora_Remark"
                  placeholder=""
                  @blur="onBlur({ rowIndex, row, col })"
                >
                </t-input>
                <span v-else>{{ row.F_ora_Remark }}</span>
              </template>
            </t-table>
          </div>
        </t-collapse-panel>
      </t-collapse>
    </div>

    <div style="display: flex; flex-direction: row; justify-content: center; margin-top: 30px"></div>

    <mater-select-dialog ref="MaterSelectDialogRef" :filter-obj="{ FIsMainPrd: 1 }" @on-confirm="onMaterSelected" />

    <mater-select-dialog
      ref="subMaterSelectDialogRef"
      :filter-obj="{ FIsMainPrd: 0 }"
      @on-confirm="onSubMaterSubSelected"
    />
    <upload-dialog
      ref="uploadRef"
      :dl-url="filePrefix + '物料清单分录模板.xlsx'"
      :upload-url="API_URL + 'pbom/uploadPbom'"
      :form-data="formData"
      @upload-success="loadData"
    />
    <project-select-dialog ref="projectSelectDialogRef" @on-confirm="onProjectSelected" />
  </div>
</template>
<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { MessagePlugin } from 'tdesign-vue-next';
import { queryMaterMeta, queryPbomList, queryPbom, savePbom, addPbom, delPbom } from '@/service/pbom';
import { API_URL, filePrefix } from '@/common/constants';
import UploadDialog from '@/components/uploadDialog/index.vue';

import MaterSelectDialog from '@/components/materSelectDialog/index.vue';
import ProjectSelectDialog from '@/components/projectSelectDialog/index.vue';

import { subcolumns } from './columns/index';

export default {
  components: { MaterSelectDialog, ProjectSelectDialog, UploadDialog },
  setup(props, { emit }) {
    const formData = reactive({ FBILLTYPE: 'WLQD01_SYS' });
    const isDetail = ref(false);
    const MaterSelectDialogRef = ref();
    const FBILLTYPE_list = ref();
    const FNumber = ref();
    const route = useRoute();
    const metaData = ref({});
    const router = useRouter();
    const draftSaving = ref(false);
    const isSaving = ref(false);
    const subDataList = ref([{ index: 0 }]);
    const oldDataList = ref([]);

    const loading = ref(false);
    const tableLoading = ref(false);
    const loadingText = ref('加载中...');
    const subMaterSelectDialogRef = ref();
    const tableSelectIndex = ref(0);
    const projectSelectDialogRef = ref(null);
    const selectedRowKeys = ref([]);
    const uploadRef = ref();

    const clickCancel = () => {
      router.go(-1);
    };

    const clickSave = async (isDraft) => {
      loading.value = true;
      loadingText.value = '正在保存中...';
      try {
        let res = null;

        if (FNumber.value) {
          // 更新
          const dataChanged = [];
          for (let index = 0; index < subDataList.value.length; index++) {
            const element = subDataList.value[index];
            if (!element.FEntryID) {
              dataChanged.push(element);
              continue;
            }
            const currItems = oldDataList.value.filter((item) => item.FEntryID === element.FEntryID);
            if (currItems[0]) {
              const currItem = currItems[0];
              if (
                currItem.FNumerator !== element.FNumerator ||
                currItem.FDenominator !== element.FDenominator ||
                currItem.F_ora_Base !== element.F_ora_Base ||
                currItem.FPositionNO !== element.FPositionNO ||
                currItem.F_NY_ZB !== element.F_NY_ZB ||
                currItem.F_ora_BaseProperty1 !== element.F_ora_BaseProperty1
              ) {
                dataChanged.push(element);
              }
            }
          }
          console.log('dataChanged:', dataChanged);

          // if (1 === 1) {
          //   return;
          // }
          if (!dataChanged[0]) {
            loading.value = false;
            MessagePlugin.error(`清单无修改！`);
            return;
          }

          res = await savePbom({
            ...formData,
            FTreeEntity: subDataList.value,
            is_draft: isDraft,
          });
        } else {
          res = await addPbom({
            ...formData,
            FTreeEntity: subDataList.value,
            is_draft: isDraft,
          });
        }
        if (res.success) {
          emit('updateData');
          MessagePlugin.success('保存成功！');
          loadData();
          // router.go(-1);
        } else {
          MessagePlugin.error(`保存失败:${res.msg}`);
        }
      } catch (e) {
        MessagePlugin.error(`保存失败:${e}`);
      } finally {
        loading.value = false;
      }
    };
    const clickUpload = () => {
      uploadRef.value.openExcelDialog();
    };
    const loadMaterMeta = async () => {
      const res = await queryMaterMeta();
      if (res) {
        metaData.value = res.data;
      }
    };
    const loadData = async (number) => {
      if (!number) {
        number = FNumber.value;
      }
      tableLoading.value = true;
      selectedRowKeys.value = [];
      const res = await queryPbom({ FNumber: number });
      if (res.dataList[0]) {
        Object.assign(formData, res.dataList[0]);
        for (let index = 0; index < res.dataList.length; index++) {
          const element = res.dataList[index];
          element.index = index;
        }
        subDataList.value = res.dataList;
        oldDataList.value = JSON.parse(JSON.stringify(res.dataList));
      } else {
        subDataList.value = [{ index: 0 }];
        emit('updateData');
        router.go(-1);
      }
      tableLoading.value = false;
    };

    const isShowSpan = computed(() => (is_extr) => {
      if (is_extr) {
        return !FNumber.value;
      }
      return !isDetail.value;
    });

    const clickShowMaterSelect = () => {
      MaterSelectDialogRef.value.openGroupDialog();
    };

    const clickShowSubMaterSelect = (index, row) => {
      tableSelectIndex.value = index;
      console.log('tableSelectIndex', tableSelectIndex.value);
      subMaterSelectDialogRef.value.openGroupDialog();
    };

    const clickShowProjectSelect = (index, row) => {
      tableSelectIndex.value = index;
      console.log('tableSelectIndex', tableSelectIndex.value);
      projectSelectDialogRef.value.openGroupDialog();
    };

    const onMaterSelected = async (material) => {
      Object.assign(formData, {
        FMATERIALID: material.FMATERIALID,
        FMaterialNumber: material.FNumber,
        FITEMNAME: material.FName,
        FITEMMODEL: material.FSpecification,
        FITEMPPROPERTY: material.FErpClsID,
        FITEMPPROPERTY_NAME: material.FErpClsName,
      });
      console.log('onMaterSelected', JSON.stringify(formData));
    };

    const onSubMaterSubSelected = (material) => {
      const index = tableSelectIndex.value;
      const row = subDataList.value[index];
      console.log('row', index);
      const freeEntity = {
        FMATERIALIDCHILD: material.FMATERIALID,
        FCHILDITEMNAME: material.FName,
        FCHILDITEMMODEL: material.FSpecification,
        FErpClsNameCHILD: material.FErpClsName,
        FCHILDITEMPROPERTY_NAME: material.FErpClsName,
        FMATERIALIDCHILDNumber: material.FNumber,
        // FMATERIALTYPE: material[''],
      };
      console.log('freeEntity', freeEntity);

      Object.assign(row, freeEntity);

      console.log('onMaterSelected', JSON.stringify(row));
    };

    const onProjectSelected = (project) => {
      console.log('onProjectSelected');

      const index = tableSelectIndex.value;
      const row = subDataList.value[index];
      const selectJson = {
        F_ora_Base: project.project_no,
        F_ora_Base_Name: project.project_name,
      };
      Object.assign(row, selectJson);
    };

    const cellClick = ({ row, col, rowIndex, colIndex, e }) => {
      console.log('cellClick', col.colKey);
      const key = `${col.colKey}Show`;
      row[key] = true;
      console.log('row', row);
    };

    const onBlur = ({ row, col, rowIndex, colIndex }) => {
      const key = `${col.colKey}Show`;
      row[key] = false;
      console.log('eee');
    };

    onMounted(() => {
      const { id } = route.params;
      isDetail.value = route.name == 'materialDetail';
      console.log('isDetail');
      if (id) {
        FNumber.value = id;
        loadData(FNumber.value);
      }
      loadMaterMeta();
    });
    const rehandleSelectChange = (value, { selectedRowData }) => {
      selectedRowKeys.value = value;
      console.log('rehandleSelectChange', value);
    };

    const sortSubData = () => {
      for (let index = 0; index < subDataList.value.length; index++) {
        const element = subDataList.value[index];
        element.index = index;
      }
    };
    const addRow = () => {
      subDataList.value.push({ index: subDataList.value.length });
      sortSubData();
    };
    const deleteRow = async () => {
      if (selectedRowKeys.value.length == 0) {
        MessagePlugin.error('未选择行');
        return;
      }
      // const selectRows = subDataList.value.filter((item) => selectedRowKeys.value.indexOf(item.index));
      const rowIndex = selectedRowKeys.value[0];
      const row = subDataList.value[rowIndex];
      if (row.FENTRYID) {
        loading.value = true;
        loadingText.value = '正在删除';
        const res = await delPbom(row.FID, row.FNumber, row.FENTRYID);
        if (res.success) {
          loadData(FNumber.value);
        } else {
          MessagePlugin.error(`删除失败:${res.msg}`);
        }
        loading.value = false;
      } else {
        subDataList.value.splice(rowIndex - 1, 1);
        sortSubData();
      }
    };

    const insertRow = () => {
      if (selectedRowKeys.value.length == 0) {
        MessagePlugin.error('未选择行');
        return;
      }
      console.log('insertRow');
      const rowIndex = selectedRowKeys.value[0];
      subDataList.value.splice(rowIndex, 0, {});
      sortSubData();
    };

    const copyRow = () => {
      if (selectedRowKeys.value.length == 0) {
        MessagePlugin.error('未选择行');
        return;
      }
      const rowIndex = selectedRowKeys.value[0];
      subDataList.value.push({
        ...subDataList.value[rowIndex],
        FENTRYID: null,
        FReplaceGroup: subDataList.value.length + 1,
      });
      // subDataList.value.splice(rowIndex, 0, { ...subDataList.value[rowIndex],'FENTRYID':null });
      sortSubData();
    };

    const swapArray = (arr, index1, index2) => {
      console.log('swapArray', arr, arr.length, index1, index2);
      if (index1 < 0 || index2 < 0) {
        return;
      }
      if (index1 >= arr.length || index2 >= arr.length) {
        return;
      }
      [arr[index1], arr[index2]] = [arr[index2], arr[index1]];
    };

    const upRow = () => {
      if (selectedRowKeys.value.length == 0) {
        MessagePlugin.error('未选择行');
        return;
      }
      const rowIndex = selectedRowKeys.value[0];
      swapArray(subDataList.value, rowIndex - 1, rowIndex - 2);
      sortSubData();
    };
    const downRow = () => {
      if (selectedRowKeys.value.length == 0) {
        MessagePlugin.error('未选择行');
        return;
      }
      const rowIndex = selectedRowKeys.value[0];
      swapArray(subDataList.value, rowIndex - 1, rowIndex);
      sortSubData();
    };

    const getRowInex = (childId) => {
      for (let index = 0; index < subDataList.value.length; index++) {
        const element = subDataList.value[index];
        if (element.FMATERIALIDCHILD == childId) {
          return index;
        }
      }
      return 0;
    };

    return {
      FNumber,
      formData,
      isDetail,
      clickCancel,
      clickSave,
      isShowSpan,
      MaterSelectDialogRef,
      clickShowMaterSelect,
      onMaterSelected,
      FBILLTYPE_list,
      metaData,
      draftSaving,
      isSaving,
      loadData,
      columns: subcolumns,
      subDataList,
      loading,
      tableLoading,
      loadingText,
      subMaterSelectDialogRef,
      tableSelectIndex,
      onSubMaterSubSelected,
      clickShowSubMaterSelect,
      cellClick,
      onBlur,
      onProjectSelected,
      projectSelectDialogRef,
      clickShowProjectSelect,
      addRow,
      deleteRow,
      insertRow,
      copyRow,
      upRow,
      downRow,
      selectedRowKeys,
      API_URL,
      rehandleSelectChange,
      uploadRef,
      clickUpload,
    };
  },
};
</script>
<style>
.form_col {
  margin-top: 10px;
}

.info_span {
  font-size: 18px;
  font-weight: bold;
}
</style>
